package com.pd.service;


import com.pd.rpc.BizEnum;
import com.pd.rpc.SeqGeneration;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by dong peng on 2018/6/7.
 */
public class SeqByRedisImpl implements SeqGeneration {


    private final String keyPrefix = "SeqGeneration.nextId";

    private String[] padStr = new String[]{"","0","00","000","0000","00000","000000","0000000"};


    @Override
    public String nextId(BizEnum bizCode) {
        return generateBizSeqNo(bizCode);
    }

    @Autowired
    private JedisPool jedisPool;

    /**
     * 业务流水号(唯一标示一笔业务)
     * 由业务前缀(2字符,参见BizEnum)+日期时间(yyyyMMdd)+流水号(8位数字)组成
     *
     * @return
     */
    public  String generateBizSeqNo(BizEnum constant){

        String curDate = fmtDate();
        String key = keyPrefix + "." + constant.name() + "." + curDate;

        Jedis jedis = null;
        String num = "";
        try {
            jedis = jedisPool.getResource();
            Long count = jedis.incr(key);
            num = String.valueOf(count);
            if(count > 99999999) {
                jedis.del(key);
            }
        }finally {
            if(jedis != null) {
                jedis.close();
            }
        }

        int preLen = 8 - num.length();
        StringBuffer sb = new StringBuffer(constant.name());
        sb.append(curDate)
                .append(padStr[preLen])
                .append(num);

        return sb.toString();
    }

    private String fmtDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        return format.format(new Date());
    }


}
